﻿using System.Windows;
using Loki.Utils;

namespace Loki.UI.Wpf
{
    public class WpfBootStrapper<TMainViewModelType> : LokiObject, IPlatform
        where TMainViewModelType : class, IScreen
    {
        private object mainObject;

        private WpfSignalManager signals = new WpfSignalManager();

        private WpfTemplatingEngine templates = new WpfTemplatingEngine();

        private WpfThreadingContext threading = new WpfThreadingContext();

        private WpfWindowManager windows = new WpfWindowManager();

        public WpfBootStrapper()
        {
            BootStrapper = new BootStrapperAdapter<TMainViewModelType>(this);
            if (!windows.DesignMode)
            {
                templates.Initialize();

                if (Application.Current != null)
                {
                    Application.Current.Startup += Application_Startup;
                }
            }
        }

        public object MainObject
        {
            get
            {
                return mainObject;
            }

            set
            {
                Application.Current.MainWindow = Templates.GetTemplate(value) as Window;
                mainObject = value;
            }
        }

        public ISignalManager Signals
        {
            get { return signals; }
        }

        public virtual ITemplatingEngine Templates
        {
            get { return templates; }
        }

        public IThreadingContext Threading
        {
            get { return threading; }
        }

        public IWindowManager Windows
        {
            get { return windows; }
        }

        protected BootStrapperAdapter<TMainViewModelType> BootStrapper { get; private set; }

        public void Run(string[] args)
        {
            signals.OnApplicationStart(new StartupEventArgs() { Parameters = args });
        }

        private void Application_Startup(object sender, System.Windows.StartupEventArgs e)
        {
            signals.OnApplicationStart(new StartupEventArgs() { Parameters = e.Args });
        }
    }
}